import store from "../store/index.js"; // @ts-ignore
import {
	state
} from "../store/smartFlight";
import IncommingHandler from "./dataHandler";

// export interface CommandNotification {
// 	commandCode ;
// 	commandName ;
// 	sendTime : number;
// 	error ?: boolean;
// }

class MyWebsocketConnector {
	static ws;

	static wsurl;

	constructor() {
		MyWebsocketConnector.ws = undefined;
	}

	static setupWebSocket(url) {
		MyWebsocketConnector.wsurl = url;
		// const ws = new WebSocket(url);
		const ws = uni.connectSocket({
			url: url,
			success: (socketTask) => {
				// 返回实例
				return socketTask
			},
		});
		console.log(ws, 'ws')
		ws.onMessage(env => {
			const data = JSON.parse(env.data);
			const id = data.nestid;
			console.log(id)
			state.nestInfo.forEach((info) => {
				if (id === info.id) {
					info.timestamp = new Date().getTime();
				}
			});
			IncommingHandler.HandleIncomming(data);
		})
		// ws.onMessage = (env) => {
		// 	const data = JSON.parse(env.data);
		// 	const id = data.nestid;
		// 	// wslog(data);
		// 	//这里定时器轮循检查基站是否离线
		// 	state.nestInfo.forEach((info) => {
		// 		if (id === info.id) {
		// 			info.timestamp = new Date().getTime();
		// 		}
		// 	});
		// 	IncommingHandler.HandleIncomming(data);
		// };

		ws.onClose(res => {
			console.log("Mywebsocket closed...");
			setTimeout(() => {
				console.log("Setting up new Mywebsocket ...");
				MyWebsocketConnector.setupWebSocket(MyWebsocketConnector.wsurl);
			}, 1000);
		})
		// ws.onClose = () => {
		// 	console.log("Mywebsocket closed...");
		// 	setTimeout(() => {
		// 		console.log("Setting up new Mywebsocket ...");
		// 		MyWebsocketConnector.setupWebSocket(MyWebsocketConnector.wsurl);
		// 	}, 1000);
		// };
		ws.onError(res => {
			console.error("Socket encountered error: ", err.message, "Closing socket");
			MyWebsocketConnector.ws.close();
		})
		// ws.onError = (err) => {
		// 	// @ts-ignore
		// 	console.error("Socket encountered error: ", err.message, "Closing socket");
		// 	MyWebsocketConnector.ws.close();
		// };

		MyWebsocketConnector.ws = ws;
	}

	static sendMessage(t, p, commandName = "", id = "") {
		const content = {
			topic: t,
			payload: JSON.stringify(p),
			id
		};
		// console.log(MyWebsocketConnector.ws)
		const payloadjson = p;
		const pyaloadCode = payloadjson.code;
		console.log(pyaloadCode);
		store.commit("commandStatus/pushCommand", {
			topic: t,
			code: pyaloadCode
		});
		store.dispatch("commandStatus/pushCommandCode", pyaloadCode);
		MyWebsocketConnector.ws.send({
			data: JSON.stringify(content)
		});

		// 实现命令发送状态显示：此处记录 命令代码, commandName还有当前时刻作为发送时间, 保存至vuex, 开一个array, 叫做消息发送队列
		// 排除一些命令
		if (pyaloadCode !== "11004" && pyaloadCode !== "16028" && pyaloadCode !== "99003") {
			store.commit("pushCmdToNotifyWaitQueue", {
				commandCode: pyaloadCode,
				commandName,
				sendTime: Date.now()
			});
		}
	}
}

export default MyWebsocketConnector;